"""
@Project:p8项目
@File:jwt_auth.py
@Author:柴奇峰
@Date:16:05
"""
from flask import current_app
import jwt
from datetime import datetime, timedelta


def generate_token(payload, expiry, algorithm="HS256"):
    """生成token"""
    key = current_app.config.get("SECRET_KEY")
    if 'exp' not in payload:
        payload['exp'] = expiry

    try:
        token = jwt.encode(payload, key, algorithm)
        return token
    except Exception as e:
        print("生成token报错》》》》》》》》》》》", e)


def check_token(token):
    """校验token"""
    key = current_app.config.get("SECRET_KEY")
    payload = jwt.decode(token, key, algorithms="HS256")
    return payload


def _generate_token(payload, is_refresh=True):
    # 设置有效期
    expiry = datetime.utcnow() + timedelta(hours=2)
    token = "JWT" + generate_token(payload, expiry)

    if is_refresh:
        expiry = datetime.utcnow() + timedelta(days=15)
        # 给payload添加标识
        payload.update({"is_refresh": True})
        refresh_token = "JWT" + generate_token(payload, expiry)

    else:
        refresh_token = None

    return token , refresh_token